//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
        type: mime
    });
}
function upload_image(elem, showElem, imgHtml) {
    $(elem).bind('change', function (e) {
        let file = e.target.files[0];
        if (file.size == 0) {
            alert('照片上传失败，上传的照片无效');
            $(this).val() == '';
        } else {
            console.log('image   ' + $(this).val());
            //图片方向角 added by lzk
            let Orientation = null;
            let inputFileInfo = $(this).val();
            let that = this;
            //$("#loadingState").show();
            //获取照片方向角属性，用户旋转控制
            EXIF.getData(file, function () {
                EXIF.getAllTags(this);
                Orientation = EXIF.getTag(this, 'Orientation');
                var reader1 = new FileReader();
                var re = reader1.readAsDataURL(file);
                var image = new Image();
                //定义流对象事件
                reader1.onload = function (e) {
                    image.src = this.result;
                }
                // 缩放图片需要的canvas
                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                // 定义image 事件
                //base64地址图片加载完毕后
                var compressoption = {
                    maxWidth: 400,
                    maxHeight: 400,
                    quality: 0.7
                }
                image.onload = function () {
                    //// 图片原始尺寸
                    var originWidth = this.width;
                    var originHeight = this.height;
                    // 最大尺寸限制
                    var maxWidth = compressoption.maxWidth || 400,
                        maxHeight = compressoption.maxHeight || 400;
                    // 目标尺寸
                    var targetWidth = originWidth,
                        targetHeight = originHeight;
                    // 图片尺寸超过400x400的限制
                    if (originWidth > maxWidth || originHeight > maxHeight) {
                        if (originWidth / originHeight > maxWidth / maxHeight) {
                            // 更宽，按照宽度限定尺寸
                            targetWidth = maxWidth;
                            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                        } else {
                            targetHeight = maxHeight;
                            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                        }
                    }
                    // canvas对图片进行缩放
                    canvas.width = targetWidth;
                    canvas.height = targetHeight;
                    // 清除画布
                    context.clearRect(0, 0, targetWidth, targetHeight);
                    // 图片压缩
                    context.drawImage(image, 0, 0, targetWidth, targetHeight);
                    //修复ios
                    var dataURL = "";
                    if (navigator.userAgent.match(/iphone/i)) {
                        // console.log('iphone');
                        //alert(expectWidth + ',' + expectHeight);
                        //如果方向角不为1，都需要进行旋转 added by lzk
                        if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                            // alert('旋转处理');
                            switch (Orientation) {
                                case 6: //需要顺时针（向左）90度旋转
                                    // alert('需要顺时针（向左）90度旋转');
                                    rotateImg(this, 'left', canvas);
                                    break;
                                case 8: //需要逆时针（向右）90度旋转
                                    // alert('需要顺时针（向右）90度旋转');
                                    rotateImg(this, 'right', canvas);
                                    break;
                                case 3: //需要180度旋转
                                    // alert('需要180度旋转');
                                    rotateImg(this, 'right', canvas); //转两次
                                    rotateImg(this, 'right', canvas);
                                    break;
                            }
                        }
                        dataURL = canvas.toDataURL("image/jpeg", 0.7);
                    } else if (navigator.userAgent.match(/Android/i)) { // 修复android
                        dataURL = canvas.toDataURL(compressoption.mime || "image/jpeg", compressoption.quality || 0.7);
                    } else {
                        //alert(Orientation);
                        if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                            //alert('旋转处理');
                            switch (Orientation) {
                                case 6: //需要顺时针（向左）90度旋转
                                    rotateImg(this, 'left', canvas);
                                    break;
                                case 8: //需要逆时针（向右）90度旋转
                                    rotateImg(this, 'right', canvas);
                                    break;
                                case 3: //需要180度旋转
                                    rotateImg(this, 'right', canvas); //转两次
                                    rotateImg(this, 'right', canvas);
                                    break;
                            }
                        }

                        dataURL = canvas.toDataURL("image/jpeg", 0.7);
                    }
                    let image_html = `<div class="image_item">
                    <img class="upload_image" src="${dataURL}">
                    <i class="iconfont icon-shanchu image_delete"></i>
                </div>`
                    $(showElem).append(image_html);
                    $(".add_image_wrapper").hide();
                    // canvas压缩并上传
                    var fileObject = dataURLtoFile(dataURL, file.name);
                    // console.log(fileObject);
                    var formdata = new FormData();
                    formdata.append('fileType', 'img'); //文件格式
                    formdata.append('fileType_file', fileObject);
                    formdata.append('method', 'upload');
                    console.log('fileType_file', fileObject);
                    $(elem).val("");
                    // $("#loadingState").show();
                    // 							$.ajax({
                    // 								url: "/Handle/Dis.ashx",
                    // 								method: 'POST',
                    // 								processData: false,
                    // 								contentType: false,
                    // 								cache: false,
                    // 								data: formdata
                    // 							}).done((response) => {
                    // 								let data = JSON.parse(response);
                    // 
                    // 								if (data.Result == true) {
                    // 									let path = data.Data[0].Path;
                    // 									var formdata2 = new FormData();
                    // 									formdata2.append('fileType', 'LSN');
                    // 									formdata2.append('fileType_file', path);
                    // 									formdata2.append('method', 'Distinguish');
                    // 									$.ajax({
                    // 										url: "/Handle/Dis.ashx",
                    // 										method: 'POST',
                    // 										processData: false,
                    // 										contentType: false,
                    // 										cache: false,
                    // 										data: formdata2
                    // 									}).done((response) => {
                    // 										$("#loadingState").hide();
                    // 										let data2 = JSON.parse(response);
                    // 										if (data2.Result == true) {
                    // 											let LSN = data2.Data;
                    // 											$("#Key").val(LSN);
                    // 											$("#search-btn-id").trigger("click");
                    // 										} else {
                    // 											alert(data2.Data);
                    // 										}
                    // 
                    // 									}).fail((err) => {
                    // 										console.log(err);
                    // 									})
                    // 								} else {
                    // 									alert('上传图片无效!请重新上传');
                    // 								}
                    // 
                    // 
                    // 							}).fail((err) => {
                    // 								console.log(err);
                    // 							})

                }
            });
        }
    });
}